package qc.module.platform.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import qc.common.core.exception.QCPromptException;

import java.util.List;

/**
 * RestTemplate调用WeiXin微服务接口统一处理类，controller中需要调用WeiXin微服务中的接口均使用此类中的方法
 *
 * @author QuCheng Tech
 * @since 2025/3/4
 */
@Service
public class RestTemplateWeiXin {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 远程调用微信小程序用户接口中获取用户手机号
     *
     * @param code 前端onGetPhoneNumber得到的e.detail.code
     * @return 用户手机号
     * @author QuCheng Tech
     * @since 2024/9/25
     */
    public String getPhoneByCode(String appId, String code) throws QCPromptException {
        List<ServiceInstance> instances = discoveryClient.getInstances("module-wx");
        //如果获取到的微服务的实例数为0，抛出异常提示
        if (instances == null || instances.size() < 0x1)
            throw new QCPromptException("调用module-wx微服务时无任何有效的实例。");

        ServiceInstance service = instances.get(0);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/user/" + appId + "/phone?appid=" + appId + "&code=" + code;

        HttpEntity<String> formEntity = new HttpEntity<String>(null, null);
        ParameterizedTypeReference<String> responseType = new ParameterizedTypeReference<String>() {
        };

        ResponseEntity<String> response = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.GET,
                formEntity,
                responseType
        );
        String resultDto = response.getBody();
        //解析返回结果，获取用户手机号
        String phone = null;
        Object jsonObject = JSON.parse(resultDto);
        if (jsonObject instanceof JSONObject) {
            JSONObject phoneJsonObject = (JSONObject) jsonObject;
            if (phoneJsonObject != null) {
                //Object phone = phoneJsonObject.get("phoneNumber");//用户绑定的手机号（国外手机号会有区号）
                phone = phoneJsonObject.get("purePhoneNumber").toString();//没有区号的手机号
                System.out.println("phone:" + phone);
            }
        }
        return phone;
    }
}
